package com.example.plugin.hook.proxy;

import java.util.List;

import android.content.Context;
import android.util.AndroidRuntimeException;

import com.example.plugin.compat.ActivityManagerNativeCompat;
import com.example.plugin.compat.IActivityManagerCompat;
import com.example.plugin.compat.SingletonCompat;
import com.example.plugin.hook.HookHandler;
import com.example.plugin.hook.handler.ActivityManagerHookHandler;
import com.example.plugin.reflect.FieldUtils;
import com.example.plugin.reflect.Utils;
import com.example.plugin.utils.MyProxy;

public class ActivityManagerHook extends ProxyHook {

	public ActivityManagerHook(Context context) {
		super(context);
	}

	@Override
	public HookHandler createHookHandler() {
		// TODO Auto-generated method stub
		return new ActivityManagerHookHandler(mContext);
	}

	@Override
	public void onInstall() throws Throwable {
		// TODO Auto-generated method stub
		Class<?> cls = ActivityManagerNativeCompat.Class();
		Object gDefault = FieldUtils.readStaticField(cls, "gDefault");

		if (gDefault == null) {
			ActivityManagerNativeCompat.getDefault();
			gDefault = FieldUtils.readStaticField(cls, "gDefault");
		}

		// 为兼容低版本
		if (IActivityManagerCompat.isIActivityManager(gDefault)) {
			setOldObj(gDefault);
			Class<?> objClass = mOldObj.getClass();
			List<Class<?>> interfaces = Utils.getAllInterfaces(objClass);
			Object proxiedActivityManager = MyProxy.newProxyInstance(
					objClass.getClassLoader(), interfaces, this);
			FieldUtils
					.writeStaticField(cls, "gDefault", proxiedActivityManager);
		} else if (SingletonCompat.isSingleton(gDefault)) {
			Object mInstance = FieldUtils.readField(gDefault, "mInstance");
			if (mInstance == null) {
				SingletonCompat.get(gDefault);
				mInstance = FieldUtils.readField(gDefault, "mInstance");
			}
			setOldObj(mInstance);
			List<Class<?>> interfaces = Utils.getAllInterfaces(mOldObj
					.getClass());
			final Object object = MyProxy.newProxyInstance(mOldObj.getClass()
					.getClassLoader(), interfaces, this);

			FieldUtils.writeField(gDefault, "mInstance", object);
		} else {
			throw new AndroidRuntimeException(
					"Can not install IActivityManagerNative hook");
		}
	}

}
